/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.fyx.secure.web.user;

import java.util.Arrays;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.fyx.core.PermissionDeniedException;
import org.fyx.mula.ejb.MulaLocal;
import org.fyx.secure.controll.SecureUserFacadeLocal;
import org.fyx.secure.entity.SecureGroup;
import org.fyx.secure.entity.SecureUser;
import org.fyx.secure.ejb.SecureLocal;
import org.fyx.secure.ejb.SecureRoles;
import org.fyx.util.FyxUtility;
import org.fyx.web.context.WebContext;

/**
 *
 * @author xljan
 */
@ManagedBean
@SessionScoped
public class SecureUserEdit {
    private SecureUser user;
    private SecureGroup[] selectedGroups;
    @EJB
    private MulaLocal mula;
    @EJB
    private SecureUserFacadeLocal secureUserFacade;
    @EJB
    private SecureLocal secure;
    

    @PostConstruct
    public void postConstruct(){
        FyxUtility.checkRole(SecureRoles.USER_EDIT_MANAGER);
    }
    
    public void initUser(int idUser) {
        user = secureUserFacade.find(idUser);
        selectedGroups = user.getSecureGroupCollection().toArray(
                new SecureGroup[user.getSecureGroupCollection().size()]);
    }

    public SecureUser getUser() {
        return user;
    }

    public SecureGroup[] getSelectedGroups() {
        return selectedGroups;
    }

    public void setSelectedGroups(SecureGroup[] selectedGroups) {
        this.selectedGroups = selectedGroups;
    }
    
    public void edit() throws PermissionDeniedException{
        checkPermisson();
        user.getSecureGroupCollection().clear();
        user.getSecureGroupCollection().addAll(Arrays.asList(selectedGroups));
        secureUserFacade.edit(user);
        FacesMessage msg = new FacesMessage(mula.get("Save sucessfull."));
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }
    
    public void checkPermisson() throws PermissionDeniedException{
        if(!WebContext.getCurrentContext().isUserInRole(SecureRoles.USER_EDIT_MANAGER)){
            throw new PermissionDeniedException();
        }
    }
}
